package cc.rengu.igas.route.core.realize.payment.impl.ncqs;

import cc.rengu.igas.channel.ncqs.biz.impl.NcqsPayServiceImpl;
import cc.rengu.igas.channel.ncqs.facade.base.Header;
import cc.rengu.igas.channel.ncqs.facade.bean.RiskInfo;
import cc.rengu.igas.channel.ncqs.facade.request.NcqsAgreePaySignWithSmsAcqRequest;
import cc.rengu.igas.channel.ncqs.facade.response.NcqsAgreePaySignWithSmsAcqResponse;
import cc.rengu.igas.channel.ncqs.facade.result.Result;
import cc.rengu.igas.route.common.constant.SmartRouteParamConstant;
import cc.rengu.igas.route.common.enums.SmartRouteRspEnums;
import cc.rengu.igas.route.core.realize.payment.DstChannelPaymentSignService;
import cc.rengu.igas.route.facade.request.IntelligencePaymentSignRequest;
import cc.rengu.igas.route.facade.request.IntelligenceResultQueryRequest;
import cc.rengu.igas.route.facade.response.IntelligencePaymentSignResponse;
import cc.rengu.igas.route.facade.response.IntelligenceResultQueryResponse;
import cc.rengu.igas.share.common.constant.ShareParamConstant;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.common.enums.AcctTypeEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.BeanUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 无卡快捷协议支付签约触发短信实现
 *
 * @author xionglz
 * @version 1.0
 * @date 2020-5-25
 */
public class NcqsPaymentSignServiceImpl implements DstChannelPaymentSignService {
    private final static String TXN_NUM = "0001";
    private RgLogger rglog = RgLog.getLogger(this.getClass().getSimpleName());

    @Override
    public IntelligencePaymentSignResponse paymentSign(IntelligencePaymentSignRequest intelligencePaymentSignRequest) throws Exception {
        NcqsAgreePaySignWithSmsAcqRequest ncqsAgreePaySignWithSmsAcqRequest = new NcqsAgreePaySignWithSmsAcqRequest();
        IntelligencePaymentSignResponse intelligencePaymentSignResponse = new IntelligencePaymentSignResponse();
        intelligencePaymentSignResponse.setHeader(intelligencePaymentSignRequest.getHeader());
        //商户号补充到15位
        if (intelligencePaymentSignRequest.getMchntNo().length() < 15) {
            ncqsAgreePaySignWithSmsAcqRequest.setCupsMchntNo(intelligencePaymentSignRequest.getMchntNo() + String.format("%0" + (15 - intelligencePaymentSignRequest.getMchntNo().length()) + "d", 0));
        } else if (intelligencePaymentSignRequest.getMchntNo().length() > 15) {
            ncqsAgreePaySignWithSmsAcqRequest.setCupsMchntNo(intelligencePaymentSignRequest.getMchntNo().substring(intelligencePaymentSignRequest.getMchntNo().length() - 15));
        } else {
            ncqsAgreePaySignWithSmsAcqRequest.setCupsMchntNo(intelligencePaymentSignRequest.getMchntNo());
        }
        ncqsAgreePaySignWithSmsAcqRequest.setMchntName(intelligencePaymentSignRequest.getMchntName());
        ncqsAgreePaySignWithSmsAcqRequest.setMchntType("4816");
        //从业务类型转换来
        ncqsAgreePaySignWithSmsAcqRequest.setBusiType("300001");
        //全额消费
        ncqsAgreePaySignWithSmsAcqRequest.setBusiFuncType("111011");
        //单位结算卡
        if (AcctTypeEnum.OTHER_PUB_ACCT.getAcctType().equals(intelligencePaymentSignRequest.getPayerInfo().getAcctType())) {
            ncqsAgreePaySignWithSmsAcqRequest.setCorpName(intelligencePaymentSignRequest.getPayerInfo().getAcctName());
            //单位结算卡证件id填写营业执照号
            ncqsAgreePaySignWithSmsAcqRequest.setLicenceNo(intelligencePaymentSignRequest.getPayerInfo().getCertId());
        } else {
            ncqsAgreePaySignWithSmsAcqRequest.setPayAcctName(intelligencePaymentSignRequest.getPayerInfo().getAcctName());
            ncqsAgreePaySignWithSmsAcqRequest.setPayAcctNo(intelligencePaymentSignRequest.getPayerInfo().getAcctNo());
//            ncqsAgreePaySignWithSmsAcqRequest.setCertType(intelligencePaymentSignRequest.getPayerInfo().getCertType());
            ncqsAgreePaySignWithSmsAcqRequest.setCertType("01");
            if (!StringUtil.isEmptyOrNull(intelligencePaymentSignRequest.getPayerInfo().getCertId())) {
                ncqsAgreePaySignWithSmsAcqRequest.setCertNo(intelligencePaymentSignRequest.getPayerInfo().getCertId());
            }
            if (!StringUtil.isEmptyOrNull(intelligencePaymentSignRequest.getPayerInfo().getPhoneNo())) {
                ncqsAgreePaySignWithSmsAcqRequest.setPhoneNo(intelligencePaymentSignRequest.getPayerInfo().getPhoneNo());
            }
            if (!StringUtil.isEmptyOrNull(intelligencePaymentSignRequest.getPayerInfo().getCardExpr())) {
                ncqsAgreePaySignWithSmsAcqRequest.setExprDate(intelligencePaymentSignRequest.getPayerInfo().getCardExpr());
            }
            if (!StringUtil.isEmptyOrNull(intelligencePaymentSignRequest.getPayerInfo().getCardCvn2())) {
                ncqsAgreePaySignWithSmsAcqRequest.setCvn2(intelligencePaymentSignRequest.getPayerInfo().getCardCvn2());
            }
        }
        SysParamService sysParamService = new SysParamServiceImpl();
        SysParam sysParam = sysParamService.getSysParamInfo(intelligencePaymentSignRequest.getHeader().getInstId(), SmartRouteParamConstant.OPMS_SYS_PARAM, SmartRouteParamConstant.NCQS_INST_CODE);
        if (null == sysParam || StringUtil.isEmptyOrNull(sysParam.getParamValue())) {
            rglog.error("未获取到<{}>机构转换为银联无卡快捷数据或者机构转换数据不存在", intelligencePaymentSignRequest.getHeader().getInstId());
            throw new BizException(SmartRouteRspEnums.CONFIG_ERROR.getRespCode(), SmartRouteRspEnums.CONFIG_ERROR.getRespDesc());
        }
        ncqsAgreePaySignWithSmsAcqRequest.setCupsInstCode(sysParam.getParamValue());
        RiskInfo riskInfo = new RiskInfo();
        ncqsAgreePaySignWithSmsAcqRequest.setRiskInfo(riskInfo);
        //设置请求头
        Header header = new Header();
        BeanUtil.beanCopy(intelligencePaymentSignRequest.getHeader(), header);
        header.setTxnNum(TXN_NUM);
        if (!StringUtil.isEmptyOrNull(intelligencePaymentSignRequest.getAdditionInfo())) {
            JSONObject jsonObject = JSON.parseObject(intelligencePaymentSignRequest.getAdditionInfo());
            if (null != jsonObject) {
                String esbSequenceNumber = jsonObject.getString(ShareParamConstant.ESB_SEQUENCE_NUMBER);
                if (!StringUtil.isEmptyOrNull(esbSequenceNumber)) {
                    header.setTraceNo(esbSequenceNumber);
                }
            }
        }

        ncqsAgreePaySignWithSmsAcqRequest.setHeader(header);
        ncqsAgreePaySignWithSmsAcqRequest.setNcqsReserve(intelligencePaymentSignRequest.getAdditionInfo());
        //调用通道签约
        DubboService dubboService = new DubboServiceImpl();
        Result<NcqsAgreePaySignWithSmsAcqResponse> signWithSmsAcqRspResult = (Result<NcqsAgreePaySignWithSmsAcqResponse>)
                dubboService.callDubboInnerMethod(NcqsPayServiceImpl.class, "agreePaySignWithSms", ncqsAgreePaySignWithSmsAcqRequest);
        if (!signWithSmsAcqRspResult.isSuccess() || null == signWithSmsAcqRspResult.getResult()) {
            rglog.error("交易未应答信息");
            throw new BizException(SmartRouteRspEnums.TRANS_TO.getRespCode(), SmartRouteRspEnums.TRANS_TO.getRespDesc());
        }
        intelligencePaymentSignResponse.setRespCode(signWithSmsAcqRspResult.getResult().getRespCode());
        intelligencePaymentSignResponse.setRespDesc(signWithSmsAcqRspResult.getResult().getRespDesc());
        intelligencePaymentSignResponse.setDstChannelId("NCQS");
        if (OltpRpcdEnum.TRANS_SUCCESS.getRespCode().equals(signWithSmsAcqRspResult.getResult().getRespCode())) {
            intelligencePaymentSignResponse.setDstChannelSsn(signWithSmsAcqRspResult.getResult().getSettleKey());
            intelligencePaymentSignResponse.setVerifyMode("01");
            //至少校验三要素，借记卡校验姓名、证件类型、证件号码、手机号；信用卡校验姓名、手机号、卡有效期、CVN2；手机号必须校验
            String valBitMap = signWithSmsAcqRspResult.getResult().getValBitMap();
            if ('1' != valBitMap.charAt(2)) {
                throw new BizException(SmartRouteRspEnums.VERIFY_NOT_ENOUGH.getRespCode(), SmartRouteRspEnums.VERIFY_NOT_ENOUGH.getRespDesc());
            }
            //存储下来
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("channelSeqNum", signWithSmsAcqRspResult.getResult().getChannelSeqNum());
            jsonObject.put("settleKey", signWithSmsAcqRspResult.getResult().getSettleKey());
            jsonObject.put("smsKey", signWithSmsAcqRspResult.getResult().getSmsKey());
            jsonObject.put("acctType", signWithSmsAcqRspResult.getResult().getAcctType());
            jsonObject.put("valBitMap", valBitMap);
            intelligencePaymentSignResponse.setAdditionInfo(jsonObject.toJSONString());
        }
        return intelligencePaymentSignResponse;
    }

    @Override
    public IntelligenceResultQueryResponse query(IntelligenceResultQueryRequest resultQueryRequest) throws Exception {
        return null;
    }
}
